// src/components/OriginChart.jsx
import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';
import 'echarts-gl';
import { originTheme, applyOriginStyle } from '../styles/originTheme';

const OriginChart = ({
  options,
  width = '100%',
  height = '400px',
  style,
  className,
  onChartReady,
  is3D = false,
  chartType = 'default', // 新增参数用于区分不同类型的3D图表
  showExportButton = true // 新增参数控制是否显示导出按钮
}) => {
  const chartRef = useRef(null);
  const chartInstance = useRef(null);
  const containerRef = useRef(null);

  // 导出图表为图片
  const exportChart = () => {
    if (!chartInstance.current) return;

    try {
      // 获取图表的 base64 数据 URL
      const dataURL = chartInstance.current.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#ffffff'
      });

      // 创建一个临时链接元素
      const link = document.createElement('a');
      link.download = 'echarts图片.png';//设置导出文件的名称。
      link.href = dataURL;
      
      // 触发下载
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error('导出失败:', error);
    }
  };

  useEffect(() => {
    if (!chartRef.current) return;

    // 注册主题
    if (!is3D) {
      try {
        echarts.registerTheme('origin', originTheme);
      } catch (e) {
        console.warn('Theme already registered');
      }
    }

    // 初始化图表，3D图表使用WebGL渲染器
    if (!chartInstance.current) {
      chartInstance.current = echarts.init(chartRef.current, is3D ? null : 'origin', {
        renderer: is3D ? 'webgl' : 'canvas'
      });
    }

    // 应用样式并设置选项
    let finalOptions = options;
    if (is3D && chartType === 'pie3D') {
      // 3D饼图特殊处理
      finalOptions = {
        ...options,
        series: options.series.map(series => ({
          ...series,
          type: 'pie',
          selectedMode: 'single',
          selectedOffset: 10,
          clockwise: true,
          startAngle: 90,
          radius: ['40%', '55%'],
          itemStyle: {
            ...series.itemStyle,
            borderWidth: 1,
            borderColor: '#fff'
          },
          label: {
            ...series.label,
            position: 'outside'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '14',
              fontWeight: 'bold'
            }
          }
        }))
      };
    } else if (!is3D) {
      finalOptions = applyOriginStyle(options, false);
    }

    chartInstance.current.setOption(finalOptions, true);

    // 图表就绪回调
    if (onChartReady) {
      onChartReady(chartInstance.current);
    }

    // 响应式调整
    const handleResize = () => {
      chartInstance.current?.resize();
    };
    window.addEventListener('resize', handleResize);

    // 清理函数
    return () => {
      window.removeEventListener('resize', handleResize);
      if (chartInstance.current) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, [options, onChartReady, is3D, chartType]);

  return (
    <div ref={containerRef} style={{ position: 'relative', width, height }}>
      <div
        ref={chartRef}
        style={{ width: '100%', height: '100%', ...style }}
        className={className}
      />
      {showExportButton && (
        <button
          onClick={exportChart}
          style={{
            position: 'absolute',
            top: '-30px',
            left: '-20px',
            padding: '6px 12px',
            backgroundColor: '#fff',
            border: '1px solid #000',
            borderRadius: '4px',
            cursor: 'pointer',
            fontSize: '14px',
            zIndex: 100,
            display: 'flex',
            alignItems: 'center',
            gap: '4px'
          }}
        >
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" stroke="#000" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            <path d="M7 10l5 5 5-5" stroke="#000" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            <path d="M12 15V3" stroke="#000" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
          导出
        </button>
      )}
    </div>
  );
};

export default OriginChart;